package basicobject

import (
	"yizhuoyan/go-study/pdfgo/characterset"
	"yizhuoyan/go-study/pdfgo/handyio"
)

type HexString struct {
	value []byte
}

var (
	hexUppercaseBytes = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}
	hexLowercaseBytes = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
)

func (this *HexString) Serialize(w handyio.PdfRawWriter) error {
	w.WriteByte('<')
	for _, b := range this.value {
		w.WriteByte(hexUppercaseBytes[b>>4])
		w.WriteByte(hexUppercaseBytes[b^0xf])
	}
	w.WriteBytes(this.value)
	w.WriteByte('>')
	return nil
}
func (this *HexString) UnSerialize(r handyio.PdfRawReader) error {
	startAt := r.IndexCurrent()
	if !r.NextByteEquals('<') {
		return r.NotSupport("非<开头")
	}
	rst := r.NextBytes(func(b byte) int {
		if characterset.IsWhiteSpaceChar(b) {
			return handyio.ReadByteSkip
		}
		if characterset.IsHexChar(b) {
			return handyio.ReadNext
		}
		return handyio.ReadStop
	})
	if !r.NextByteEquals('>') {
		_ = r.IndexMoveTo(startAt)
		return r.NotSupport("非>结尾")
	}
	//奇数添加0
	if len(rst)%2 == 1 {
		rst = append(rst, '0')
	}
	this.value = rst
	return nil
}
